// pages/lunch/lunch.js
const util = require('../../utils/util.js');
const app = getApp();
const key = app.globalData.key;
const resurl = app.globalData.resurl;
var blueBg = 'rgba(43, 117, 240, 1)';
var grayBg = 'rgba(213, 213, 213, 1)';
let interstitialAd = null;
Page({

  /**
   * 页面的初始数据
   */

  data: {
    isDelay: '',
    adverShow: true,
    bannerShow: true,
    showFinish: false,
    showMiss: false,
    show: false,
    showMask: false,
    timeShow: false,
    showMaskNext: false,
    timeyuanbao: '',
    userMoney: '',
    money: app.globalData.money,
    clocktxt: '',
    order: '',
    count: '',
    isClock: false,
    background: '',
    clockInList: [],
    event: [
      {
        different: '早餐',
        time: '06:30-08:30',
        benefit: '早餐不仅能够源源不断的给人们提供能量，补充身体所需要的阳气，如果不吃早餐，身体所需的能量难以得到补充，同时不吃早餐的话也会使人容易发胖，长期下来会对肠胃造成不好的影响',
        mealImg: '/images/image_meal_middle_1.png',
      },
      {
        different: '中餐',
        time: '11:30-13:00',
        benefit: '中午吃饭可以给身体补充能量，并在注意力开始松懒时提高血糖水平，如果感觉昏昏欲睡，吃一小份午餐也有助于恢复精力并帮助做好下午工作的准备。此外，吃午餐还能保持新陈代谢活跃',
        mealImg: '/images/image_meal_middle_2.png',
      },
      {
        different: '晚餐',
        time: '18:00-20:00',
        benefit: '晚餐的作用，四分之一是维持生命，四分之三是维持医生的收入。所以，重视晚餐，就是重视你的未来',
        mealImg: '/images/image_meal_middle_3.png',
      },

    ],
    srcList: [
      '/images/image_meal_3.png',
      '/images/image_meal_3.png',
      '/images/image_meal_3.png',
    ],
    imgList: [
      '/images/image_meal_1.png',
      '/images/image_meal_2.png',
      '/images/image_meal_3.png',
      '/images/image_meal_4.png',
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(blueBg);
    let now = new Date();
    let hours = now.getHours();
    let minutes = now.getMinutes();
    let [...srcList] = [...this.data.srcList];
    let [...imgList] = [...this.data.imgList];
    //开始时间
    var time_begin = function (beginTime) {
      var strb = beginTime.split(":");
      if (strb.length != 2) {
        return false;
      }
      var b = new Date();
      b.setHours(strb[0]);
      b.setMinutes(strb[1]);
      var btimestamp = b.getTime();
      return btimestamp;
    }
    //console.log(time_begin ("06:00"));
    //console.log(now.getTime());
    //结束时间
    var time_end = function (endTime) {
      var stre = endTime.split(":");
      if (stre.length != 2) {
        return false;
      }
      var e = new Date();
      e.setHours(stre[0]);
      e.setMinutes(stre[1]);
      var etimestamp = e.getTime();
      return etimestamp;
    }
    //console.log(time_end ("08:30"));
    var timestamp = now.getTime();
    //早餐
    if (timestamp < time_begin("06:30")) {
      this.setData({
        order: 0,
      })
    }
    else if (timestamp > time_begin('06:30') && timestamp < time_end('08:30')) {
      srcList.splice(0, 1, imgList[0]);
      this.setData({
        order: 0,
        clocktxt: '早餐打卡',
        count: 0,
        isClock: true,
      })
    }
    else if (timestamp > time_begin('08:30')) {
      this.setData({
        order: 0,
      })
    }
    //中餐
    if (timestamp > time_begin('11:30') && timestamp < time_end('13:00')) {
      srcList.splice(1, 1, imgList[0]);
      this.setData({
        order: 1,
        count: 1,
        isClock: true,
      })
    }
    else if (timestamp > time_begin('13:00') && timestamp < time_end('18:00')) {
      srcList.splice(1, 1, imgList[3]);
      this.setData({
        order: 1,
      })
    }
    //晚餐
    if (timestamp > time_begin('18:00') && timestamp < time_end('20:00')) {
      srcList.splice(2, 1, imgList[0]);
      this.setData({
        order: 2,
        count: 2,
        isClock: true,
      })
    }
    else if (timestamp > time_begin('20:00')) {
      srcList.splice(2, 1, imgList[3]);
      this.setData({
        order: 2,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  back: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  insertScreenAD: function () {
    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-1cc4cb154d00aa08'
      })
      interstitialAd.onLoad(() => { })
      interstitialAd.onError((err) => { })
      interstitialAd.onClose(() => { })
    }

    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
  },
  //打卡点击事件
  clock: function (e) {
    var that = this;
    var srcList = e.currentTarget.dataset.srclist;
    var imgList = e.currentTarget.dataset.imglist;
    var order = e.currentTarget.dataset.order;
    var clocktxt = e.currentTarget.dataset.clocktxt;
    var clockInList = e.currentTarget.dataset.clockinlist;
    srcList.splice(order, 1, imgList[1]);
    that.setData({
      srcList,
      clocktxt: '已打卡',
      background: blueBg,
      isClock: false,
    })
    that.clockEat(clockInList[order].id, order)//调用打卡接口 15
  },
  // 显示领取元宝奖励的弹窗
  timeToast: function (a) {
    var that = this;
    var money = that.data.money;
    app.globalData.money = money + a;
    that.setData({
      timeShow: true,
      showMaskNext: true,
      money: app.globalData.money,
      timeyuanbao: a,
    })
    var userMoney = Math.floor((app.globalData.money) / 10000 * 100) / 100;
    that.setData({
      userMoney: userMoney,
    })
  },
  // 关闭领取奖励的弹窗
  clickcloseReward: function () {
    var that = this;
    var isDelay = that.data.isDelay;
    if(isDelay == 1) {
      var delayTimer = setInterval(function () {
        that.setData({
          timeShow: false,
          showMaskNext: false,
        })
        clearInterval(delayTimer);
      },2000)
    } else {
      that.setData({
        timeShow: false,
        showMaskNext: false,
      })
    }
  },
  //吃饭打卡 接口15
  clockEat: function (jobId, order) {
    var that = this;
    var money = that.data.money;
    var userId = wx.getStorageSync("userId");
    var data15 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId: userId,
        jobId: jobId,
      }
    }
    data15 = JSON.stringify(data15);
    data15 = util.base64_encode(data15);
    data15 = util.xxtea_encrypt(data15, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=15&a=1&b=2',
      data: data15,
      header: {
        "content-type": "application/json",
        "dataType": "json",
      },
      method: "post",
      success: function (res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        if (res.resultCode === 0) {
          res = JSON.parse(res.data);
          console.log(res);
          that.timeToast(res.reward);
          app.globalData.money = money + res.reward;
          var clockInList = that.data.clockInList;
          clockInList[order].clockType = 1;
          that.setData({
            clockInList: clockInList,
            money: app.globalData.money,
          })
        }
        console.log(clockInList[order].clockType);
      }
    })
  },
  // 关闭banner广告
  adClose: function () {
    this.setData({
      adverShow: false,
      // videoShow: true,
    })
  },
  //显示打卡时间已经错过
  missToast: function () {
    var that = this;
    that.setData({
      showMask: true,
      showMiss: true,
    })
  },
  //显示打卡时间未到
  futureToast: function () {
    var that = this;
    that.setData({
      showMask: true,
      show: true,
    })
  },
  // 已完成打卡弹窗
  finishToast: function () {
    var that = this;
    that.setData({
      showFinish: true,
      showMask: true,
    })
  },
  // 关闭时间未到和时间已经的弹窗
  close: function () {
    var that = this;
    var isDelay = wx.getStorageSync("isDelay");
    if(isDelay == 1) {
      var delayTimer = setInterval(function () {
        that.setData({
          show: false,
          showMiss: false,
          showMask: false,
          showFinish: false,
          bannerShow: true,
        })
        clearInterval(delayTimer);
      },2000)
    } else {
      that.setData({
        show: false,
        showMiss: false,
        showMask: false,
        showFinish: false,
        bannerShow: true,
      })
    }
  },
  closeBanner: function () {
    this.setData({
      bannerShow: false,
    })
  },
  choose: function (e) {
    var that = this;
    let event = e.currentTarget.dataset.event;
    let clocktxt = e.currentTarget.dataset.clocktxt;
    let index = e.currentTarget.dataset.index;
    that.getEatInfo(index);
    // console.log(index);
    let now = new Date();
    let timeStamp = now.getTime();

    var beginTime = function (begintime) {
      var bArray = begintime.split(":");
      //console.log(bArray);
      if (bArray.length !== 2) {
        return false;
      }
      var b = new Date();
      b.setHours(bArray[0]);
      b.setMinutes(bArray[1]);
      var btimeStamp = b.getTime();
      return btimeStamp;
    }
    var endTime = function (endtime) {
      var eArray = endtime.split(":");
      if (eArray.length !== 2) {
        return false;
      }
      var e = new Date();
      e.setHours(eArray[0]);
      e.setMinutes(eArray[0]);
      var etimesTamp = e.getTime();
      return etimesTamp;
    }
    //早
    if (index === 0) {
      if (timeStamp < beginTime("06:30")) {
        that.setData({
          order: 0,
        })
      }
      else if (timeStamp > beginTime("06:30") && timeStamp < endTime("08:30")) {
        that.setData({
          order: 0,
        })
      }
      else if (timeStamp > endTime("08:30")) {
        that.setData({
          order: 0,
          background: grayBg,
        })
      }
    }
    //中
    if (index === 1) {
      if (timeStamp < beginTime('11:30')) {
        that.setData({
          order: 1,
        })
      }
      else if (timeStamp > beginTime('11:30') && timeStamp < endTime('13:00')) {
        that.setData({
          order: 1,
        })
      }
      else if (timeStamp > endTime('13:00')) {
        that.setData({
          order: 1,
          background: grayBg,
        })
      }
    }
    if (index === 2) {
      if (timeStamp < beginTime('18:00')) {
        that.setData({
          order: 2,
        })
      }
      else if (timeStamp > beginTime('18:00') && timeStamp < endTime('20:00')) {
        that.setData({
          order: 2,
        })
      }
      else if (timeStamp > endTime('20:00')) {
        that.setData({
          order: 2,
          background: grayBg,
        })
      }
    }
  },
  // 获取吃饭打卡显示页面，用于底部点击的显示状态
  getEatInfo: function (index) {
    //获取喝水打卡页面 接口14
    var that = this;
    var userId = wx.getStorageSync("userId");
    var data14 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId: userId,
        clockType: 13,
      }
    }
    data14 = JSON.stringify(data14);
    data14 = util.base64_encode(data14);
    data14 = util.xxtea_encrypt(data14, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=14&a=1&b=2',
      data: data14,
      header: {
        "content-type": "application/json",
        "dataType": "json",
      },
      method: "post",
      success: function (res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        if (res.resultCode === 0) {
          res = JSON.parse(res.data);
          console.log(res);
          if (res.clockInList[index].clockType === 0) {
            that.missToast();
            that.setData({
              clocktxt: '已错过',
              background: grayBg,
              isClock: false,
            })
          } else if (res.clockInList[index].clockType === 1) {
            that.finishToast();
            that.setData({
              clocktxt: '已打卡',
              background: blueBg,
              isClock: false,
            })
          } else if (res.clockInList[index].clockType === 2) {
            that.futureToast();
            that.setData({
              clocktxt: '未到时间',
              background: grayBg,
              isClock: false,
            })
          } else if (res.clockInList[index].clockType === 3) {
            if (index === 0) {
              that.setData({
                clocktxt: '早餐打卡',
                background: blueBg,
                isClock: true,
              })
            } else if (index === 1) {
              that.setData({
                clocktxt: '午餐打卡',
                background: blueBg,
                isClock: true,
              })
            } else {
              that.setData({
                clocktxt: '晚餐打卡',
                background: blueBg,
                isClock: true,
              })
            }
          }
          that.setData({
            clockInList: res.clockInList,
          })
        }
      }
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取吃饭打卡页面 接口14
    var that = this;
    var isDelay = wx.getStorageSync("isDelay");
    that.setData({
      money: app.globalData.money,
      isDelay,
    })
    var beginTime = function (begintime) {
      var bArray = begintime.split(":");
      //console.log(bArray);
      if (bArray.length !== 2) {
        return false;
      }
      var b = new Date();
      b.setHours(bArray[0]);
      b.setMinutes(bArray[1]);
      var btimeStamp = b.getTime();
      return btimeStamp;
    }
    var now = new Date();
    var timeStamp = now.getTime();
    var nowNum;
    if (timeStamp < beginTime("06:30")) {
      nowNum = 1;
    }
    if (timeStamp > beginTime("06:30")) {
      nowNum = 1;
    }
    if (timeStamp > beginTime("11:30")) {
      nowNum = 2;
    }
    if (timeStamp > beginTime("18:00")) {
      nowNum = 3;
    }

    var userId = wx.getStorageSync("userId");
    var data14 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId: userId,
        clockType: 13,
      }
    }
    data14 = JSON.stringify(data14);
    data14 = util.base64_encode(data14);
    data14 = util.xxtea_encrypt(data14, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=14&a=1&b=2',
      data: data14,
      header: {
        "content-type": "application/json",
        "dataType": "json",
      },
      method: "post",
      success: function (res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        if (res.resultCode === 0) {
          res = JSON.parse(res.data);
          console.log(res);
          var lastestSrc = that.data.lastestSrc;

          var imgList = that.data.imgList;
          var srcList = that.data.srcList;

          for (var index = 0; index < nowNum; index++) {
            if (res.clockInList[index].clockType === 0) {
              srcList.splice(index, 1, imgList[3]);
              that.setData({
                clocktxt: '已错过',
                srcList,
                background: grayBg,
                isClock: false,

              })
            } else if (res.clockInList[index].clockType === 1) {
              srcList.splice(index, 1, imgList[1]);
              that.setData({
                clocktxt: '已打卡',
                srcList,
                background: blueBg,
                isClock: false,
              })
            } else if (res.clockInList[index].clockType === 2) {
              srcList.splice(index, 1, imgList[2]);
              that.setData({
                clocktxt: '未到时间',
                srcList,
                background: grayBg,
                isClock: false,
              })
            } else if (res.clockInList[index].clockType === 3) {
              if (index === 0) {
                that.setData({
                  clocktxt: '早餐打卡',
                  background: blueBg,
                  isClock: true,
                })
              } else if (index === 1) {
                that.setData({
                  clocktxt: '午餐打卡',
                  background: blueBg,
                  isClock: true,
                })
              } else {
                that.setData({
                  clocktxt: '晚餐打卡',
                  background: blueBg,
                  isClock: true,
                })
              }
              srcList.splice(index, 1, imgList[0]);
              that.setData({
                srcList,
              })
            }
          }
          that.setData({
            clockInList: res.clockInList,
          })
        }
      }
    })
    var count = 0;
    var insertScreenAdTimer = setInterval(function () {
      count ++;
      console.log(count);
      if(count > 3) {
        that.insertScreenAD();
        clearInterval(insertScreenAdTimer);
      }
    },1000)
    that.insertScreenAdTimer = insertScreenAdTimer;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    clearInterval(that.insertScreenAdTimer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    clearInterval(that.insertScreenAdTimer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})